package org.pvt.model.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.pvt.model.HasName;

/**
 * @author Pavel Talanov
 */
public final class DBUtils {

    private DBUtils() {
    }

    @Nullable
    private static SQLiteDatabase writableDB = null;
    @Nullable
    private static SQLiteDatabase readableDB = null;

    @NotNull
    public static SQLiteDatabase getWritableDB(@NotNull Context context) {
        if (readableDB != null) {
            readableDB.close();
            readableDB = null;
        }
        if (writableDB != null) {
            return writableDB;
        }
        writableDB = (new OpenHelper(context)).getWritableDatabase();
        return writableDB;
    }

    @NotNull
    public static SQLiteDatabase getReadableDB(@NotNull Context context) {
        if (writableDB != null) {
            writableDB.close();
            writableDB = null;
        }
        if (readableDB != null) {
            return readableDB;
        }
        readableDB = (new OpenHelper(context)).getReadableDatabase();
        return readableDB;
    }

    @NotNull
    public static String getName(@NotNull Cursor cursor) {
        int nameColumn = cursor.getColumnIndex(HasName.NAME);
        return cursor.getString(nameColumn);
    }
}
